package com.luqili.utils.pub.crypto;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 求Hash的工具
 *
 * @author luqili
 */
public class HashUtils {

    public static String TYPE_MD2 = "MD2";
    public static String TYPE_MD5 = "MD5";
    public static String TYPE_SHA_1 = "SHA-1";
    public static String TYPE_SHA_224 = "SHA-224";
    public static String TYPE_SHA_256 = "SHA-256";
    public static String TYPE_SHA_384 = "SHA-384";
    public static String TYPE_SHA_512 = "SHA-512";

    public static byte[] md5(byte[] data) {
        return hashType(data, TYPE_MD5);
    }

    /**
     * 返回小写的16进制数
     *
     * @param data
     * @return
     */
    public static String md5ToHex(byte[] data) {
        return hashTypeToHex(data, TYPE_MD5);
    }

    /**
     * 返回大写的16进制数
     *
     * @param data
     * @return
     */
    public static String md5ToHexUpperCase(byte[] data) {
        return hashTypeToHex(data, TYPE_MD5).toUpperCase();
    }

    public static byte[] sha1(byte[] data) {
        return hashType(data, TYPE_SHA_1);
    }

    public static String sha1ToHex(byte[] data) {
        return hashTypeToHex(data, TYPE_SHA_1);
    }

    public static byte[] sha256(byte[] data) {
        return hashType(data, TYPE_SHA_256);
    }

    public static String sha256ToHex(byte[] data) {
        return hashTypeToHex(data, TYPE_SHA_256);
    }

    /**
     * 求指定类型的HASH
     *
     * @param file
     * @param type {@link https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest}
     * @return
     */
    public static String hashTypeToHex(byte[] data, String type) {
        return Hex.encodeHexString(hashType(data, type));
    }

    /**
     * 求指定类型的HASH
     *
     * @param file
     * @param type {@link https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#MessageDigest}
     * @return
     */
    public static byte[] hashType(byte[] data, String type) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(type);
            return md.digest(data);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("不支持的加密类型:" + type);
        }

    }
}
